#!/sbin/openrc-run
# Copyright 1999-2016 Gentoo Foundation
# Distributed under the terms of the GNU General Public License, v2

# Hint: We don't use start-stop-daemon, because pidfile is the same
# for every irattach instance. So it isn't reliable if we have more
# than one IrDA device (i.e. with IrDA-USB).

depend() {
	use serial
}

checkconfig() {
	if [ -z "${DEVICE}" ]; then
		DEVICE="/dev/ttyS1"
	fi

	if [ -z "${DONGLE}" -o "${DONGLE}" = "none" ]; then
		DONGLE=""
	else
		DONGLE="-d ${DONGLE}"
	fi

	if [ "${DISCOVERY}" = "yes" ]; then
		DISCOVERY="-s"
	else
		DISCOVERY=""
	fi

	NET_IRDA_OPTS=""

	# Set maximum baud rate for IrDA
	if [ -n "${MAX_BAUD_RATE}" ]; then
		NET_IRDA_OPTS="${NET_IRDA_OPTS} net.irda.max_baud_rate=${MAX_BAUD_RATE}"
	fi

	# Disable discovery (enabling is done automatically by irattach)
	if [ -z "${DISCOVERY}" ]; then
		NET_IRDA_OPTS="${NET_IRDA_OPTS} net.irda.discovery=0"
	fi

	# Ensure that SIR driver is loaded (needed for pmac_zilog)
	case "${DEVICE}" in
		/dev/ttyS*) LOAD_MODULES="${LOAD_MODULES} irtty-sir";;
	esac
}

remove_module() {
	local CNT=0
	while ! /sbin/modprobe -sqr ${1}; do
		[ $((CNT++)) -eq 10 ] && break
		sleep 0.25
	done
}

start() {
	checkconfig
	ebegin "Starting IrDA"

	# Needed for some machines in FIR-mode
	[ -n "${SETSERIAL}" ] && /bin/setserial ${SETSERIAL} uart none port 0x0 irq 0

	# Load IrDA modules
	/sbin/modprobe -sqa ircomm-tty ${LOAD_MODULES}

	# Set IrDA options
	[ -n "${NET_IRDA_OPTS}" ] && /sbin/sysctl -e -q -w ${NET_IRDA_OPTS}

        # Finally, attach IrDA device
	/usr/sbin/irattach ${DEVICE} ${DONGLE} ${DISCOVERY}
	eend ${?}
}

stop() {
	ebegin "Shutting down IrDA"
	/usr/bin/pkill -f "^/usr/sbin/irattach ${DEVICE} ?"
	eend ${?}

	# Try to remove IrDA driver
	case "${DEVICE}" in
		/dev/ttyS*) remove_module irtty-sir;;
		irda[0-9]*) remove_module ${DEVICE};;
	esac
	return 0  # never fail
}
